package com.pearadmin.pro.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.pearadmin.pro.common.constant.SecurityConstant;
import com.pearadmin.pro.common.tools.auth.TokenUtil;
import com.pearadmin.pro.common.constant.TokenConstant;
import com.pearadmin.pro.common.security.subject.CustomUserDetails;
import com.pearadmin.pro.common.tools.web.ServletUtil;
import com.pearadmin.pro.common.web.domain.Result;
import com.pearadmin.pro.common.web.domain.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Describe: 自定义 Security 登陆成功处理类
 * Author: 就 眠 仪 式
 * CreateTime: 2019/10/23
 * */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisTemplate<String,CustomUserDetails> redisTemplate;

    /**
     * Describe: 自定义 Security 登陆成功返回结果
     * Author: 就 眠 仪 式
     * CreateTime: 2019/10/23
     * */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
            // 创建 Json Web Token
            CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal();
            String token = TokenUtil.createAccessToken(customUserDetails);
            String accessToken = TokenConstant.TOKEN_PREFIX + token;
            // 存储 Token 至 Redis
            redisTemplate.opsForValue().set(token, customUserDetails, TokenConstant.EXPIRATION, TimeUnit.SECONDS);
            // 封装返回数据
            Result result = Result.success(ResultCode.LOGIN_SUCCESS.getCode(), ResultCode.LOGIN_SUCCESS.getMessage());
            result.setToken(accessToken);
            // 返回封装数据
            ServletUtil.write(JSON.toJSONString(result));
    }
}
